package com.jty.module_user.viewmodel

import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import com.blankj.utilcode.util.GsonUtils
import com.czl.lib_base.config.AppConstants
import com.jty.lib_base.base.AppManager
import com.jty.lib_base.base.BaseBean
import com.jty.lib_base.base.BaseViewModel
import com.jty.lib_base.base.MyApplication
import com.jty.lib_base.binding.command.BindingAction
import com.jty.lib_base.binding.command.BindingCommand
import com.jty.lib_base.bus.event.SingleLiveEvent
import com.jty.lib_base.data.DataRepository
import com.jty.lib_base.event.LiveBusCenter
import com.jty.lib_base.extension.ApiSubscriptHelper
import com.jty.lib_base.utils.ComUtils
import com.jty.lib_base.utils.RxThreadHelper
import com.orhanobut.logger.Logger
import okhttp3.RequestBody


/**
 * author: zhouyh
 * created on: 2021/9/18 5:35 下午
 * description:主页viewmodel
 */
class ModifyPwdViewModel(application: MyApplication, model: DataRepository) :
    BaseViewModel<DataRepository>(application, model) {
    val loginpwd = model.getLoginPassword()
    val inOldPwd = ObservableField<String>()
    val inNew1Pwd = ObservableField<String>()
    val inNew2Pwd = ObservableField<String>()
    val eyeStateOld = ObservableBoolean(false)
    val eyeStateNew1 = ObservableBoolean(false)
    val eyeStateNew2 = ObservableBoolean(false)

    val uc = UIChangeEvent()

    override fun onCreate() {
        super.onCreate()
        tvTitle.set("修改密码")
    }

    /**
     * UI刷新事件 用于观察者
     */
    class UIChangeEvent{
        val changeEyeStateOld: SingleLiveEvent<Boolean> = SingleLiveEvent()
        val changeEyeStateNew1: SingleLiveEvent<Boolean> = SingleLiveEvent()
        val changeEyeStateNew2: SingleLiveEvent<Boolean> = SingleLiveEvent()
    }

    val onEyeClickCommandOld: BindingCommand<Boolean> = BindingCommand(BindingAction {
        if (eyeStateOld.get()){
            eyeStateOld.set(false)
        }else{
            eyeStateOld.set(true)
        }
        uc.changeEyeStateOld.postValue(eyeStateOld.get())
    })

    val onEyeClickCommandNew1: BindingCommand<Boolean> = BindingCommand(BindingAction {
        if (eyeStateNew1.get()){
            eyeStateNew1.set(false)
        }else{
            eyeStateNew1.set(true)
        }
        uc.changeEyeStateNew1.postValue(eyeStateNew1.get())
    })

    val onEyeClickCommandNew2: BindingCommand<Boolean> = BindingCommand(BindingAction {
        if (eyeStateNew2.get()){
            eyeStateNew2.set(false)
        }else{
            eyeStateNew2.set(true)
        }
        uc.changeEyeStateNew2.postValue(eyeStateNew2.get())
    })

    val modifyPwd: BindingCommand<Void> = BindingCommand(BindingAction {
        Logger.e("登录密码：${loginpwd}, 旧密码：${inOldPwd.get()}, 新密码：${inNew1Pwd.get()}, 再次输入新密码：${inNew2Pwd.get()}")
        modifyPwd()
    })

    private fun modifyPwd(){

        if(inOldPwd.get()?.trim() != loginpwd) {
            showNormalToast("原密码错误")
            return
        }
        if(inNew1Pwd.get()?.trim().isNullOrEmpty()) {
            showNormalToast("请输入新密码")
            return
        }
        if(inNew2Pwd.get()?.trim().isNullOrEmpty()) {
            showNormalToast("请输入确认密码")
            return
        }
        
        if(inNew1Pwd.get()!!.length < 6 || inNew1Pwd.get()!!.length > 12 || inNew1Pwd.get()!!.contains(" ")) {
            showNormalToast("请输入6-12位英文+数字组合")
            return
        }
        if(!inNew1Pwd.get()?.trim().equals(inNew2Pwd.get()?.trim())) {
            showNormalToast("两次输入密码不一致")
            return
        }

        val json = ComUtils.getHashmapByStr(
            arrayOf(  "oldPassword","newPassword"),
            arrayOf(inOldPwd.get().toString(),inNew1Pwd.get().toString())
        )
        val requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
            GsonUtils.toJson(json))

        model.apply {
            this.modifyPassword(requestBody)
                .compose(RxThreadHelper.rxSchedulerHelper(this@ModifyPwdViewModel))
                .doOnSubscribe { showLoading() }
                .subscribe(object : ApiSubscriptHelper<BaseBean<Any?>>() {
                    override fun onResult(t: BaseBean<Any?>) {
                        //Logger.e(t.toString())
                        dismissLoading()
                        if (t.code == 0) {
                            showNormalToast("修改成功")
                        }

                        //退出登录
                        outLoginReset()
                        model.saveAccountAndPwd(model.getLoginName()!!, inNew1Pwd.get()!!)
                        model.saveLoginState(false)
                        LiveBusCenter.postLogoutEvent(3)
                        startContainerActivity(AppConstants.Router.Login.F_LOGIN)

                        //finish()
                        AppManager.instance.finishAllActivity();
                    }

                    override fun onFailed(msg: String?) {
                        dismissLoading()
                        showNormalToast(msg)
                    }
                })
        }

    }


}